package com.fa4j.common.base.exception;

import lombok.Getter;

import java.text.MessageFormat;

@Getter
public class BaseException extends RuntimeException {

    /**
     * 错误类型
     */
    private final ErrorType errorType;

    /**
     * 错误信息
     */
    private final String errMsg;

    /**
     * 错误信息参数
     */
    private final Object[] args;

    public BaseException(ErrorType errorType, String errMsg, Object[] args, Throwable cause) {
        super(formatErrorMsg(errorType, errMsg, args), cause);
        this.errMsg = errMsg;
        this.errorType = errorType;
        this.args = args;
    }

    private static String formatErrorMsg(ErrorType errorType, String errMsg, Object[] args) {
        String errorMsg = errMsg;
        if (errorMsg == null || errorMsg.isBlank()) {
            errorMsg = errorType.getErrMsg();
        }
        if (args != null && args.length > 0) {
            errorMsg = MessageFormat.format(errorMsg, args);
        }
        return errorMsg;
    }
}
